from flask import jsonify, request


def Response(msg, code=200):
    if isinstance(msg, dict):
        return jsonify(msg), code
    else:
        return jsonify({"msg": f"{msg}"}), code

def ResponseInvalidPost():
    return Response("无效表单参数，检查required与提交参数",400)

def ResponseInvalidInstance():
    return Response("无效instance",400)

def ResponseInvalidModel():
    return Response("无效Model",400)

def ResponseInvalidCallback():
    return Response("无效callback",400)

def ResponseInvalidSession():
    return Response("无效flask session",400)

def ResponseInvalidRoute():
    return Response("无效路由",400)

def ResponsePostJson(required, _cb, optional=[]):

    overlap = set(required) & set(optional)
    if overlap:
        raise ValueError(f"Keys {overlap} appear in both required and optional lists.")

    def RequestGetJsonWithRequiredFromPost(required=[], optional=[]):
        json_data = request.get_json()

        for key in required:
            if key not in json_data:
                return None

        for key in optional:
            if key not in json_data:
                json_data[key] = None
        return json_data

    json = RequestGetJsonWithRequiredFromPost(required, optional)
    if not json and required:
        return ResponseInvalidPost()

    if _cb:
        return _cb(json)
    return ResponseInvalidCallback()

